/**
 * Copyright (c) 2015-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.admin.controller;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.common.util.HttpUtil;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import io.jboot.component.swagger.ParamType;
import io.jboot.utils.StringUtils;
import io.jboot.web.JbootRequestContext;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jplus.core.base.BaseController;
import io.jplus.core.plugin.kisso.JplusToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Api(description = "用户登录相关接口文档", basePath = "/admin", tags = "login")
@RequestMapping(value = "/admin", viewPath = "/")
public class AdminController extends BaseController {

    public final Log log = Log.getLog(AdminController.class);
    @Override
    @RequiresUser
    public void index() {
        render("index.html");
    }

    @RequiresUser
    public void main() {
        render("main.html");
    }

    @RequiresGuest
    @ApiOperation(value = "登录方法", httpMethod = "POST", notes = "user login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "用户名", paramType = ParamType.FORM, dataType = "string", required = true),
            @ApiImplicitParam(name = "password", value = "密码", paramType = ParamType.FORM, dataType = "string", required = true),
    })
    public void login(String account, String password) {
        Ret ret;
        HttpServletRequest request = JbootRequestContext.getRequest();
        HttpServletResponse response = JbootRequestContext.getResponse();
        String ip = request.getRemoteAddr();
        if (StringUtils.isBlank(account) && StringUtils.isBlank(password)) {
            render("login.html");
            return;
        }

        //验证码校验
        if (!this.validateCaptcha("captcha")) {
            render("login.html");
            return;
        }

        if (!HttpUtil.isPost(request)) {
            redirect("login.html");
        }

        UsernamePasswordToken token = new UsernamePasswordToken(account, password, false, ip);
        Subject subject = SecurityUtils.getSubject();
        String returnUrl =null;
        try {
            String referer = request.getHeader("Referer");
            if(StrKit.notBlank(referer)&&referer.indexOf("ReturnURL")!=-1){
                String tmpUrl = referer.substring(referer.indexOf("ReturnURL")+10,referer.length());
                returnUrl = HttpUtil.decodeURL(HttpUtil.decodeURL(tmpUrl));
                log.info("returnUrl="+returnUrl);
            }
            //是否需要进行验证
            if (!subject.isAuthenticated()) {
                subject.login(token);
            }
            subject.getSession().setAttribute("account", account);
            JplusToken jplusToken = new JplusToken();
            jplusToken.setAccount(account);
            jplusToken.setIp(ip);
            jplusToken.setTime(System.currentTimeMillis());
            jplusToken.setUid(getSession().getId());

            SSOHelper.setSSOCookie(request, response, jplusToken, false);

            ret = Ret.ok();
        } catch (AuthenticationException e) {
            ret = Ret.fail("message", e.getMessage());
            this.setFlashAttr("message", e.getMessage());
        } catch (Exception ex) {
            ret = Ret.fail("messiage", ex.getMessage());
            this.setFlashAttr("message", ex.getMessage());
        }

        if (isAjaxRequest()) {
            renderJson(ret);
        } else {
            if(StrKit.notBlank(returnUrl)){
                redirect(returnUrl);
            }else {
                redirect(ret.isOk() ? "/admin" : "/admin/login");
            }
        }

    }

    @RequiresUser
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        SSOHelper.clearLogin(JbootRequestContext.getRequest(), JbootRequestContext.getResponse());
        redirect(subject.isAuthenticated() ? "/admin" : "/admin/login");
    }

}
